<?php
/**
 * Copyright (c) 2020
 * 摘    要：
 * 作    者：san
 * 修改日期：2020.03.30
 */

namespace App\Middleware;

use App\Constants\Constants;
use App\Library\HttpResponse\Response;
use App\Library\Traits\Helper;
use App\Model\User;
use ErrorException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddleware implements MiddlewareInterface
{
    use Helper;

    /**
     * @Inject
     * @var Response
     */
    protected $response;

    /**
     * @var \Redis $redis
     */
    protected $redis;

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $token = $request->getHeader(Constants::X_TOKEN) ? $request->getHeader(Constants::X_TOKEN)[0] : '';

            if (!$token) {
                throw new ErrorException("403 Forbidden", 403);
            }
            $uuid = $this->tokenCheck($token);
            $user = User::findFromCache($uuid);
            if (!$user) {
                throw new ErrorException('用户不存在', 404);
            }
            Context::set('user', $user);
            return $handler->handle($request);
        } catch (\Exception $exception) {
            return $this->response->showResults($exception->getCode(), $exception->getMessage(), []);
        }
    }

    /**
     * token检测
     *
     * @param $token
     * @throws ErrorException
     * @return bool|mixed|string
     */
    public function tokenCheck($token)
    {
        $this->redis = redis();
        $uuid        = $this->redis->get(User::USER_SESSION_KEY . $token);

        if (!$uuid) {
            throw new ErrorException("token失效", 401);
        }

        return $uuid;
    }
}
